package org.phis.cloud.order.config;

import javax.annotation.PreDestroy;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;

@Configuration
public class RedissonConfig {
	
	@Autowired
	private RedissonClient redisson;

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		final RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		template.setKeySerializer(keySerializer());
		template.setValueSerializer(jsonRedisSerializer());
		template.setHashKeySerializer(jsonRedisSerializer());
		template.setHashValueSerializer(jsonRedisSerializer());
		template.setDefaultSerializer(jsonRedisSerializer());
		template.afterPropertiesSet();
		return template;
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		final StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
		return template;
	}

	@PreDestroy
	public void destroy() {
		redisson.shutdown();
	}
	
	@Bean
	public RedisSerializer<?> keySerializer() {
		return new StringRedisSerializer();
	}
	
	@Bean
	public RedisSerializer<?> jsonRedisSerializer() {
		return new GenericFastJsonRedisSerializer();
	}

}